<template>
  <div>
    <cus-Breadcrumb level1="习题管理" level2="新增习题" class="mb20"></cus-Breadcrumb>
    <!-- 单独添加 -->
    <el-card class="box-card fl" shadow="never" id="addnew">
      <div class="onlyAdd">
        <el-tag>单独添加</el-tag>
        <el-form label-width="100px">
          <!-- 分类 -->
          <el-form-item label="所属分类">
            <el-select
              allow-create
              size="small"
              default-first-option
              placeholder="请选择子字典分类"
              v-model="ChildCategory.alias"
            >
              <el-option
                v-for="item in ChildCategory"
                :key="item.id"
                :label="item.content"
                :value="item.id"
                @click.native="pushIDtoAddExeForm(item)"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题目类型">
            <el-radio
              @change="changePlaceHolderdx"
              @click.native="flag = 1"
              v-model="addExeForm.kind"
              label="0"
              value="0"
              name="radios"
            >单选题</el-radio>
            <el-radio
              @change="changePlaceHolderpd"
              @click.native="flag = 0"
              v-model="addExeForm.kind"
              label="1"
              value="0"
              name="radios"
            >判断题</el-radio>
          </el-form-item>
          <el-form-item label="题目内容" class="limit-min-width">
            <el-input
              type="textarea"
              placeholder="请将题干输入在此输入，最长支持****个中文字符"
              v-model="addExeForm.content"
            ></el-input>
          </el-form-item>
          <el-form-item label="题目选项" class="limit-min-width">
            <div>
              <el-input
                :disabled="!flag"
                class="input-con"
                :placeholder="placeholderA"
                v-model="optionObj.A.content"
              ></el-input>
              <el-radio
                :disabled="!optionObj.A.content"
                v-model="addExeForm.rightOption"
                label="A"
                class="ml10"
                @change="pushOptionTocontentA()"
              >A为正确选项</el-radio>
              <el-input
                :disabled="!flag"
                class="input-con mt10"
                :placeholder="placeholderB"
                v-model="optionObj.B.content"
              ></el-input>
              <el-radio
                :disabled="!optionObj.B.content"
                v-model="addExeForm.rightOption"
                label="B"
                class="ml10"
                @change="pushOptionTocontentB()"
              >B为正确选项</el-radio>
              <el-input
                v-if="flag"
                class="input-con mt10"
                placeholder="C选项"
                v-model="optionObj.C.content"
              ></el-input>
              <el-radio
                :disabled="!optionObj.C.content"
                v-if="flag"
                v-model="addExeForm.rightOption"
                label="C"
                class="ml10"
                @change="pushOptionTocontentC()"
              >C为正确选项</el-radio>
              <el-input
                v-if="flag"
                class="input-con mt10"
                placeholder="D选项"
                v-model="optionObj.D.content"
              ></el-input>
              <el-radio
                :disabled="!optionObj.D.content"
                v-if="flag"
                v-model="addExeForm.rightOption"
                label="D"
                class="ml10"
                @change="pushOptionTocontentD()"
              >D为正确选项</el-radio>
              <el-input
                v-if="flag"
                class="input-con mt10"
                placeholder="E选项"
                v-model="optionObj.E.content"
              ></el-input>
              <el-radio
                :disabled="!optionObj.E.content"
                v-if="flag"
                v-model="addExeForm.rightOption"
                label="E"
                class="ml10"
                @change="pushOptionTocontentE()"
              >E为正确选项</el-radio>
              <el-input
                v-if="flag"
                class="input-con mt10"
                placeholder="F选项"
                v-model="optionObj.F.content"
              ></el-input>
              <el-radio
                :disabled="!optionObj.F.content"
                v-if="flag"
                v-model="addExeForm.rightOption"
                label="F"
                class="ml10"
                @change="pushOptionTocontentF()"
              >F为正确选项</el-radio>
            </div>
          </el-form-item>
          <div class="btn-con">
            <el-button type="success" @click="addExercise" v-if="tkxzCommitOnly">提交</el-button>
            <el-button type="warning">重置</el-button>
          </div>
        </el-form>
      </div>
    </el-card>
    <!-- 上传文件添加 -->
    <el-card class="box-card pore cardHeight fr" shadow="never" id="allAdd">
      <el-tag>批量添加</el-tag>
      <el-upload
        class="upload-demo mt10"
        ref="upload"
        action
        :on-preview="handlePreview"
        :limit="3"
        :on-remove="handleRemove"
        :before-upload="beforeUpdata"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary" v-if="tkxzCommitChoose">选取Excel文件</el-button>
        <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
          v-if="tkxzCommitAll"
        >点击上传题目</el-button>
        <div slot="tip" class="el-upload__tip">只能上传Excel文件，且不超过5MB</div>
      </el-upload>
    </el-card>
  </div>
</template>
<script>
import $$ from '@/plugins/statusCode.config'
export default {
  data () {
    return {
      tkxzCommitOnly: false,
      tkxzCommitChoose: false,
      tkxzCommitAll: false,
      placeholderA: '',
      placeholderB: '',
      FatherCategory: [],
      ChildCategory: [],
      flag: 1,
      addExeForm: {
        content: '',
        kind: '',
        categoryId: '',
        rightOption: '',
        rightOptionContent: ''
      },
      optionObj: {
        A: {
          letter: 'A',
          content: ''
        },
        B: {
          letter: 'B',
          content: ''
        },
        C: {
          letter: 'C',
          content: ''
        },
        D: {
          letter: 'D',
          content: ''
        },
        E: {
          letter: 'E',
          content: ''
        },
        F: {
          letter: 'F',
          content: ''
        }
      },
      option: [],
      keyName: 'question',
      items: ''
    }
  },
  mounted () {
    this.addExeForm.kind = '0'
    this.placeholderA = 'A选项'
    this.placeholderB = 'B选项'
    this.optionObj.A.content = ''
    this.optionObj.B.content = ''
    this.role()
  },
  created () {
    this.searchChildCategory()
    this.showLoading = true
    const token = sessionStorage.getItem('accessToken')
    if (!token) {
      this.$message.warning('请先登录')
      this.$router.push({ name: 'login' })
    }
    this.managerNickName = sessionStorage.getItem('managerNickName')
  },
  methods: {
    role () {
      let arr = JSON.parse(sessionStorage.getItem('buttonRole'))
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 'tkxz-commit-only') {
          this.tkxzCommitOnly = true
        }
        if (arr[i] === 'tkxz-commit-choose') {
          this.tkxzCommitChoose = true
        }
        if (arr[i] === 'tkxz-commit-all') {
          this.tkxzCommitAll = true
        }
      }
    },
    changePlaceHolderdx () {
      this.placeholderA = 'A选项'
      this.placeholderB = 'B选项'
      this.optionObj.A.content = ''
      this.optionObj.B.content = ''
    },
    changePlaceHolderpd () {
      this.optionObj.A.content = '正确'
      this.optionObj.B.content = '错误'
      this.placeholderA = '正确'
      this.placeholderB = '错误'
    },
    pushOptionTocontentA () {
      this.addExeForm.rightOptionContent = this.optionObj.A.content
    },
    pushOptionTocontentB () {
      this.addExeForm.rightOptionContent = this.optionObj.B.content
    },
    pushOptionTocontentC () {
      this.addExeForm.rightOptionContent = this.optionObj.C.content
    },
    pushOptionTocontentD () {
      this.addExeForm.rightOptionContent = this.optionObj.D.content
    },
    pushOptionTocontentE () {
      this.addExeForm.rightOptionContent = this.optionObj.E.content
    },
    pushOptionTocontentF () {
      this.addExeForm.rightOptionContent = this.optionObj.F.content
    },
    pushIDtoAddExeForm (item) {
      this.items = item
      this.addExeForm.category = item.content
      this.addExeForm.categoryAlias = item.alias
      this.addExeForm.categoryId = item.id
    },
    // 查找子字典逻辑
    async searchChildCategory () {
      const that = this
      let param = new URLSearchParams()
      param.append('keyName', this.keyName)
      await this.$http8081
        .post(`/dictionary-search/flipListByKeyName`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  // 更新成功
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.searchChildCategory()
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  _that.$router.push({ name: 'login' })
                  _that.$message.success('登陆超时请重新登陆')
                }
              })
          }
          if (res.data.statusCode === $$.s20006) {
            that.ChildCategory = res.data.data
          }
        })
    },

    toJSONarr () {
      for (var i in this.optionObj) {
        if (this.optionObj[i].content) {
          if (typeof this.option === 'string') {
            this.option = []
            this.option.push(this.optionObj[i])
          } else {
            this.option.push(this.optionObj[i])
          }
        }
      }
      this.option = JSON.stringify(this.option)
      // console.log(JSON.parse(this.option))
    },
    // 新增习题逻辑
    async addExercise () {
      this.toJSONarr()
      if (
        this.addExeForm.content &&
        this.addExeForm.kind &&
        this.addExeForm.categoryId &&
        this.addExeForm.categoryAlias &&
        this.addExeForm.rightOption &&
        this.addExeForm.rightOptionContent
      ) {
        const that = this
        let param = new URLSearchParams()
        param.append('category', this.addExeForm.category)
        param.append('content', this.addExeForm.content)
        param.append('kind', this.addExeForm.kind)
        param.append('categoryId', this.addExeForm.categoryId)
        param.append('categoryAlias', this.addExeForm.categoryAlias)
        param.append('rightOption', this.addExeForm.rightOption)
        param.append('rightOptionContent', this.addExeForm.rightOptionContent)
        this.toJSONarr()
        param.append('choiceOptionList', this.option)
        await this.$http8080
          .post(`/question-operate/save`, param)
          .then(function (res) {
            if (res.data.statusCode === $$.s20000) {
              that.$message.success(res.data.statusMsg)
              that.option = []
              that.optionObj = {
                A: {
                  letter: 'A',
                  content: ''
                },
                B: {
                  letter: 'B',
                  content: ''
                },
                C: {
                  letter: 'C',
                  content: ''
                },
                D: {
                  letter: 'D',
                  content: ''
                },
                E: {
                  letter: 'E',
                  content: ''
                },
                F: {
                  letter: 'F',
                  content: ''
                }
              }
              that.addExeForm.content = ''
              that.addExeForm.kind = ''
              that.pushIDtoAddExeForm(that.items)
              that.addExeForm.rightOption = ''
              that.addExeForm.rightOptionContent = ''
            } else {
              that.$message.error(res.data.statusMsg)
            }
            if (res.data.statusCode === $$.s70003) {
              const id = sessionStorage.getItem('id')
              let param = new URLSearchParams()
              param.append('id', id)
              const _that = that
              return that.$refresh
                .post(`/manager-search/updateToken`, param)
                .then(function (res) {
                  if (res.data.statusCode === $$.s70005) {
                    sessionStorage.setItem(
                      'accessToken',
                      res.data.data.accessToken
                    )
                    sessionStorage.setItem(
                      'refreshToken',
                      res.data.data.refreshToken
                    )
                    _that.addExercise()
                    _that.searchChildCategory()
                  }
                  if (res.data.statusCode === $$.s70003) {
                    sessionStorage.clear()
                    _that.$router.push({ name: 'login' })
                    _that.$message.success('登陆超时请重新登陆')
                  }
                })
            }
          })
      } else {
        this.$message.error('请检查输入完整性')
      }
    },
    submitUpload () {
      this.$refs.upload.submit()
    },
    handleRemove (file, fileList) {},
    handlePreview (file) {},
    // 上传习题Excel逻辑
    beforeUpdata (file) {
      let fd = new FormData()
      fd.append('file', file)
      const that = this
      this.$http8080
        .post('/question-operate/saveFromExcel', fd)
        .then(function (res) {
          if (res.data.statusCode === $$.s20000) {
            that.$message.success(res.data.statusMsg)
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
      return false
    }
  }
}
</script>
<style>
#addnew {
  height: 845px;
  width: 52%;
}
#allAdd {
  width: 47%;
}
.onlyAdd {
  margin-bottom: 20px;
}
.onlyAddstyle {
  width: 50%;
}

.limit-min-width {
  width: 100%;
}
.el-textarea__inner {
  width: 91.8%;
  height: 50px;
}
.Preview-Area {
  width: 45%;
  height: 300px;
}
.btn-con {
  /* margin-left: 240px; */
  width: 250px;
  margin: 100px auto;
}
.btn-con button {
  margin-right: 40px;
}
.input-con {
  width: 70%;
}
</style>
